<template>
  <el-row style="height:100%">
    <page>
      <pageheader :isShow="false">
        首选店铺
      </pageheader>
      <div class="page-content-shop">
        <div class="reportthead">
          <div class="condition">
            <span class="choice-title">所属企业：</span>
            <el-cascader
              v-model="company_id_arr"
              :placeholder="'选择所属企业'"
              collapse-tags
              :options="optionsCom"
              ref="cascaderRef"
              :props="{
              expandTrigger: 'hover',
              multiple: 'true',
            }"
              @visible-change="companyVisibleChange"
              @remove-tag="companyRemoveTag"
              size="small"
              style="width:300px">
            </el-cascader>
            <span class="choice-title">案场选择：</span>
            <el-select
              v-model="case_id"
              multiple
              filterable
              collapse-tags
              clearable
              size="small"
              placeholder="请选择案场"
              style="width:300px;display: inline-block">
              <el-option
                v-for="item in optionsCase"
                :key="item.id"
                :label="item.case_name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="condition">
            <span class="choice-title">日期选择：</span>
            <el-date-picker
              v-model="datetimeval.day"
              @change="dataIsChange = true"
              type="daterange"
              align="right"
              popper-class="report-date"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              size="small">
            </el-date-picker>
          </div>
          <div class="head-row ok">
            <el-button @click="updata" class="queryReport"
                       :type="dataIsChange ? 'primary':'success'" size="small">
              <span v-if="dataIsChange"><i class="el-icon-search"></i> 查询数据</span>
              <span v-else><i class="el-icon-refresh-left"></i> 刷新数据</span>
            </el-button>
          </div>
        </div>
        <div class="hei13"></div>
        <div class="card loadingClass"
             v-loading="xxloading"
             element-loading-text="请点击查询报表获取相关数据"
             element-loading-spinner="el-icon-caret-top"
             element-loading-background="rgba(245, 248, 254, 1)" >
          <el-tabs v-model="indicator_key" type="card" @tab-click="updata">
            <el-tab-pane v-for="item in indicator_keys" :label="item.name" :key="item.key" :name="item.key">
              <el-checkbox-group
                v-model="sex"
                :min="1"
                @change="updata"
                style="display: inline-block ; margin:0px 50px">
                <el-checkbox label="0">男性</el-checkbox>
                <el-checkbox label="1">女性</el-checkbox>
              </el-checkbox-group>
              <el-checkbox-group
                v-model="age_group"
                :min="1"
                @change="updata"
                style="display: inline-block;margin: 20px">
                <el-checkbox v-for="item in ageList" :label="item.key" :key="item.key">{{item.info}}</el-checkbox>
              </el-checkbox-group>
              <el-table :data="tableData" size="small" stripe>
                <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
                <el-table-column label="店铺名称" prop="area_name" align="center"></el-table-column>
                <el-table-column label="人数" prop="person_count" align="center"></el-table-column>
                <el-table-column label="百分比" prop="ratio" align="center"></el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .reportthead {
    width: 100%;
    background: #fff;
    padding: 27px 0 20px 45px;

    .head-row {
      line-height: 36px;
      height: 36px;
      margin-bottom: 15px;
      &.ok {
        height: auto;
        min-height: 36px;
        line-height: 36px;
        text-align: center;

        .el-radio-group {
          height: 36px;
          line-height: 36px;

          .el-radio-button__inner {
            height: 36px;
            line-height: 36px;
            padding: 0;
            width: 50px;
            font-size: 12px;
          }
        }

        .queryReport {
          line-height: 36px;
          height: 36px;
          padding: 0 10px;
          margin-right: 45px;
          vertical-align: middle;
          display: inline-block;
          // background-color: #8EC5FC;
          // background-image: linear-gradient(62deg, #8EC5FC 0%, #E0C3FC 100%);
          // border-color: #8EC5FC;
          background: #545deb;
          border-color: #545deb;

          &.el-button--success {
            background: #85ce61;
            border-color: #85ce61;
          }

          span {
            color: #fff;
          }
        }
      }
    }
  }
  .page-content-shop {
    padding: 15px;
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
    .loadingClass{
      width: 100%;
      background: #fff;
      padding: 15px 10px;
      overflow: hidden;
      height: 690px;
      .el-loading-mask{
        .el-loading-spinner{
          top: 80px;
          i{
            display: none;
          }
          .el-loading-text{
            font-size: 18px;
            font-weight: bold;
            color:#b4b6bd;
          }
        }

      }
    }
  }
  .condition{
    margin-bottom: 10px;
    .choice-title{
      margin-left:10px;
    }
  }
</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import pageheader from "@/components/page/pageheader";
  import reportGlobal from "@/components/global/reportGlobal";//公共配置
  export default {
    data() {
      return {
        code: this.$route.query.code,        //通过菜单栏点击传过来的code判断使用的公共参数
        tableData:[],
        pagination:{
          total:0,//总条目数
          currentPage:1,//当前页数
          pageSize:10,//每页显示条目个数
          pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
        },
        company_id_arr:[],
        company_id:null,
        optionsCom:[],
        case_id:[],
        optionsCase:[],
        indicator_keys:[],
        indicator_key:'',
        globalIndicator_keys:[],//本地指标数组
        ageList:[],
        age_group:[],
        tags:'',
        sex:['0','1'],
        xxloading:true,
        datetimeval:{
          day:[moment(new Date()).format("YYYY-MM-DD"),moment(new Date()).format("YYYY-MM-DD")],
          hm:['00:00','23:59']
        },
        dataIsChange:true,

        pickerOptions: {                //时间日期控件规则
          disabledDate(time) {
            return time.getTime() > Date.now() - 8.64e6;   //正常 今天之前
            //  let curDate = (new Date()).getTime();
            //   let three = 14 * 24 * 3600 * 1000;
            //   let threeMonths = curDate - three;
            //   return time.getTime() > Date.now() || time.getTime() < threeMonths;
          },
        },
      }
    },
    components: {
      page,
      pageheader,
    },
    created(){
      this.getAgeList()
      this.getReady()

      //根据code来获取公共参数
      for (let i in reportGlobal.queryList) {
        if (this.code == reportGlobal.queryList[i].code) {
          this.global = reportGlobal.queryList[i]
        }
      }
      this.globalIndicator_keys = this.global.indicator_keys
      this.tags = this.global.tags.join(',')
      this.$Bus.$emit('Loading',false)
    },
    methods:{
      //获取年龄组配置
      getAgeList(){
        let url = '/sys/face_report/age_group'
        this.$api.post(url)
        .then(data=>{
          // console.log(data);
          this.ageList = data.data;
          this.age_group = this.ageList.map(x=>{
            return x.key
          })
        })
        .catch(err=>{
           console.log(err);
          this.$message.error('获取年龄组失败')
          this.$Bus.$emit('Loading', false)
        })
      },
      //获取权限下的指标
      getKpi(){
        let p = new Promise((res,rej)=>{
          let url = '/sys/report_assist_new/get_indicator_list'
          let params = {
            org_id_list : this.case_id,
            org_type : 2,
          }
          this.$api.post(url,params)
          .then(data=>{
            console.log(data,'getkpi');
            this.indicator_keys = data.data.filter(x => {
              return this.globalIndicator_keys.includes(x.key)
            })
            if(this.indicator_key == 0 || !this.indicator_key){
              this.indicator_key = this.indicator_keys[0].key
            }
            this.$nextTick(()=>{
              res()
            })
          })
          .catch(err=>{
            rej(err)
          })
        })
        return p
      },
      //页面初始化,获取企业信息，拿到第一个企业调用获取案场
      getReady(){
        let asyncFun = async ()=>{
          await this.getCompany();
          await this.getCase()
        }
        asyncFun().then(data=>{
          this.dataIsChange=true;
        })
        .catch(err=>{
          console.log(err);
          this.$message.warning(err);
        })
        this.$Bus.$emit('Loading',false);
      },
      //获取企业树
      getCompany(){
        let p = new Promise((res,rej)=>{
          let url = '/sys/report_assist_new/company_tree';
          this.$api.get(url)
          .then(data => {
            if(data){
              recursion(data.data);
              function recursion(val) {
                if(val.length){
                  for(let i in val){
                    val[i].value = val[i].id;
                    val[i].label = val[i].company_name;
                    val[i].parent_id_str = val[i].parent_name_list ? val[i].parent_name_list.join('/') : '';
                    if(val[i].children && val[i].children.length){
                      recursion(val[i].children)
                    }else{
                      delete val[i].children
                    }
                  }
                }
              }
              this.$nextTick(()=>{
                let arr = [];
                recursionData(Array.of(data.data[0]))
                function recursionData(val) {
                  if(val.length){
                    for(let i in val){
                      if(val[i].children){
                        recursionData(val[i].children)
                      }else{
                        arr.push(val[i].node_location.split('-').slice(0,-1))
                        delete val[i].children
                      }
                    }
                  }
                }
                this.optionsCom = data.data;
                let company_id_arr = [];//配置当前第一个选中的值
                arr.map(x=>{
                  for(let i = 0 ; i < x.length;i++){
                    if(x[i] == data.data[0].id){
                      company_id_arr.push(x.slice(i,x.length))
                    }
                  }
                });
                this.company_id_arr = company_id_arr;
                this.company_id = company_id_arr.join(',');
                res();
              })
            }
          })
          .catch(err=>{
            this.optionsCom = [];
            this.optionsCase = [];
            this.company_id_arr = [];
            this.company_id = null;
            this.case_id = [];
            rej('未获取到企业树')
          })
        })
        return p
      },
      //获取案场
      getCase(){
        let p = new Promise((res,rej)=>{
          let lsarr=[];
          let company_id_arr = this.company_id_arr
          for(let i in company_id_arr) {
            lsarr.push(company_id_arr[i][company_id_arr[i].length-1])
          }
          let params={
            org_id_list:lsarr,
            org_type:1
          }
          let url='/sys/report_assist_new/case_list'
          this.$api.post(url,params)
          .then(data=>{
            this.optionsCase = [];
            this.case_id = [];
            if(data.data && data.data.length){
              this.optionsCase = data.data;
              this.case_id.push(data.data[0].id);
              res();
            } else{
              this.optionsCase = [];
              this.case_id = [];
              rej('该企业下无案场')
            }
          })
          .catch(err=>{
            this.optionsCase = [];
            this.case_id = [];
            rej('该企业下无案场')
          })
        })
        return p
      },


      companyVisibleChange(val){
        if(!val){
          this.companyChange();
        }
      },
      companyRemoveTag(){
        this.$nextTick(()=>{
          if(this.company_id_arr.length){
            this.companyChange()
          }else{
            this.optionsCase=[];
            this.case_id=[];
          }
        })
      },
      companyChange(){
        if(!this.company_id_arr.length) {
          this.optionsCase=[];
          this.case_id=[];
        }
        let company_id_arr = this.company_id_arr.map(x => {
          return x.slice(-1)[0]
        });
        this.company_id = company_id_arr.join(',')
        this.getCase().then(()=>{
          this.dataIsChange=true;
        })
        .catch(err=>{
          console.log(err);
          this.$message.warning(err);
        })
      },

      updata(){
        console.log(this.case_id,'this.case_id');
        if(!this.case_id.length){
          this.$message.warning('请选择案场');
          return
        }
        this.$Bus.$emit('Loading', true)
        this.xxloading = false;
        this.isShowTable = true;
        this.dataIsChange=false;
        this.getKpi().then(()=>{
          let url = '/sys/face_report/preferred_area_list?indicator_key='+ this.indicator_key +
            '&tags='+ this.tags + '&age_group='+ this.age_group + '&sex='+ this.sex +
            '&start_day='+ this.datetimeval.day[0] + '&end_day='+ this.datetimeval.day[1] +
            '&start_hm='+ this.datetimeval.hm[0] + '&end_hm='+ this.datetimeval.hm[1]
          let params = {
            org_id_list:this.case_id,
            org_type:2
          }
          this.$api.post(url,params)
          .then(data=>{
            console.log(data,'getList');
            if(data.data){
              this.tableData = data.data.map(x=>{
                x.ratio = x.ratio + '%'
                return x
              })
            }
            this.$Bus.$emit('Loading', false)
          })
        })
        .catch(err=>{
          this.$message.error(err)
        })

      },
    }
  }
</script>

